<script setup lang="tsx">
defineOptions({
  name: "FULLSCREEN_ELECTRICTITY_OPERATION_TASKVIEW"
});
import { ref, unref, onMounted, onUnmounted, computed, reactive } from "vue";
import { useRoute } from "vue-router";
import fullScreen from "@/assets/svg/common/fullScreen.svg?component";
import { getSafeDays, updateSafeDays } from "@/api/modules/operation";
import { useRouterStoreHook } from "@/store/modules/router";
import TaskStatus from "./components/TaskStatus.vue";
import TaskCount from "./components/TaskCount.vue";
import modelBox from "@/views/common/components/modelBox/index.vue";
import safeDays from "../overview/components/safeDays.vue";
import { useFullscreen, useTransition, TransitionPresets } from "@vueuse/core";
import dayjs from "dayjs";
import { queryTaskCount, queryTaskList } from "@/api/modules/operation";
import { queryChildByTypeCodeAndItemValue } from "@/api/common";
import { PxMessage } from "px-ui";

const route = useRoute();

const routerStore = useRouterStoreHook();
const queryParams = reactive({
  pageNum: 1,
  pageSize: 10,
  clazzCode: route.query.className,
  timeRange: [dayjs().startOf("day").format("YYYY-MM-DD HH:mm:ss"), dayjs().endOf("day").format("YYYY-MM-DD HH:mm:ss")],
  taskTitle: "", //任务名称
  taskModuleTypeCode: [], //任务类型
  taskModuleSingle: "", // 查询条件里的单个code
  taskOwner: [], //执行人
  taskOwnerSingle: "", // 查询条件里的单个code
  taskStatus: [],
  taskStatusSingle: "" // 查询条件里的单个code
});
const categroyList = ref([]);
const total = ref(0);
const totalPages = ref(0);
const tableData = ref([]);
const countData = ref({});
const handleParams = () => {
  if (queryParams.taskModuleSingle) {
    queryParams.taskModuleTypeCode = [queryParams.taskModuleSingle];
  } else {
    queryParams.taskModuleTypeCode = [];
  }
  if (queryParams.taskStatusSingle) {
    queryParams.taskStatus = [queryParams.taskStatusSingle];
  } else {
    queryParams.taskStatus = [];
  }
  if (queryParams.taskOwnerSingle) {
    queryParams.taskOwner = [queryParams.taskOwnerSingle];
  } else {
    queryParams.taskOwner = [];
  }
};
const getTaskCount = async () => {
  try {
    handleParams();
    let res = await queryTaskCount({ ...queryParams, startTime: queryParams.timeRange[0], endTime: queryParams.timeRange[1] });
    let totalNum = 0;
    let undoNum = 0;
    let doneNum = 0;
    if (res && res.length) {
      categroyList.value.forEach(v => {
        let target = res.filter(r => r.taskModuleName == v.code);
        if (target && target.length) {
          v.undoTasks = target[0].undoTasks;
          v.doneTasks = target[0].doneTasks;
          v.totalTasks = target[0].totalTasks;
          totalNum += v.totalTasks;
          undoNum += v.undoTasks;
          doneNum += v.doneTasks;
        }
      });
    }
    countData.value = {
      totalNum,
      undoNum,
      doneNum
    };
  } catch (error) {}
};
const getTaskList = async () => {
  try {
    handleParams();
    let res = await queryTaskList({ ...queryParams, startTime: queryParams.timeRange[0], endTime: queryParams.timeRange[1] });
    tableData.value = res.data;
    total.value = res.total;
    totalPages.value = res.pages;
  } catch (error) {}
};
const getCategroyList = async () => {
  const data: any = await queryChildByTypeCodeAndItemValue({
    value: "MODULE",
    typeCode: "OPERATION_TASKBOARD"
  });
  if (data && data.length) {
    data.forEach(v => {
      categroyList.value.push({
        name: v.itemName,
        code: v.itemValue,
        activeStatus: ""
      });
    });
  } else {
    categroyList.value = [];
  }
  getTaskCount();
  getTaskList();
};

const { isFullscreen, toggle } = useFullscreen();
const clock = ref<string>("");
const clickTimer = ref<any>(null);
const pageTimer = ref<any>(null);
const operationDays = ref<number>(0);
const isShowSafeDays = ref<boolean>(false);
const updateTimer = ref<any>(null);

const operationDaysVal = useTransition(operationDays, {
  duration: 1000,
  transition: TransitionPresets.easeInOutExpo
});

const startClock = () => {
  clearClock();
  clickTimer.value = setInterval(async () => {
    clock.value = dayjs().format("YYYY/MM/DD HH:mm:ss");
    const hour = dayjs().get("hour");
    const minute = dayjs().get("minute");
    const second = dayjs().get("second");
    if (hour === 23 && minute === 59 && second === 59) {
      operationDays.value += 1;
      const id = 1;
      const params = { id, num: operationDays.value };
      await updateSafeDays(params);
    }
  }, 1000);
  pageTimer.value = setInterval(async () => {
    queryParams.pageNum = queryParams.pageNum + 1;
    if (queryParams.pageNum > totalPages.value) {
      queryParams.pageNum = 1;
    }
    getTaskCount();
    getTaskList();
  }, 16000);
};
const clearClock = () => {
  clearInterval(clickTimer.value);
  clearInterval(pageTimer.value);
};

const getSafeDaysFn = async () => {
  const res = await getSafeDays(1);
  if (!res) return;
  const { num } = res;
  operationDays.value = num;
};

const init = async () => {
  const title = "任务看板";
  document.title = title;
  startClock();
  await getSafeDaysFn();
};

const toFullScreen = () => {
  toggle();
};
const getNameByCode = (list, key, value, name) => {
  let nameList = [];
  if (list.length) {
    let dataList = unref(list);
    if (dataList.length) {
      let userIds = value.split(",");
      if (value) {
        userIds.forEach(item => {
          let obj = dataList.filter(v => v[key] == item);
          if (obj.length) {
            nameList.push(obj[0][name]);
          }
        });
      }
    }
  }
  return nameList.join(",");
};
onMounted(async () => {
  init();
  getCategroyList();
});

onUnmounted(() => {
  clearClock();
});
</script>

<template>
  <div class="gas-overview">
    <div class="gas-overview-item one">
      <div class="one-item">{{ clock }}</div>
      <div class="one-item one-middle">任务看板</div>
      <div class="one-item one-right">
        <div class="one-days" @click="isShowSafeDays = true">安全运行天数：{{ Math.round(operationDaysVal) }}天</div>
      </div>
    </div>
    <div class="gas-overview-item all total">
      <modelBox title="任务统计" dark>
        <TaskCount :categroyList="categroyList" :countData="countData" dark />
      </modelBox>
    </div>
    <div class="gas-overview-item all list">
      <modelBox title="任务清单" dark>
        <px-table :data="tableData" show-overflow-tooltip class="dark-table" stripe :height="'calc(100vh - 450px)'">
          <template #empty>
            <px-empty />
          </template>
          <px-table-column label="序号" width="60" align="center" fixed="left">
            <template #default="{ $index }">
              {{ (queryParams.pageNum - 1) * queryParams.pageSize + $index + 1 }}
            </template>
          </px-table-column>
          <px-table-column prop="taskId" label="任务编号" min-width="130" />
          <px-table-column prop="taskModuleName" label="任务类型" min-width="120">
            <template #default="scope">
              {{ getNameByCode(categroyList, "code", scope.row.taskModuleName, "name") || "其他任务" }}
            </template>
          </px-table-column>
          <px-table-column prop="taskTitle" label="任务名称" min-width="180" />
          <px-table-column prop="taskPlanTime" label="任务开始时间" min-width="140">
            <template #default="scope">
              {{ scope.row.taskPlanTime || "-" }}
            </template>
          </px-table-column>
          <px-table-column prop="taskFinishTime" label="任务结束时间" min-width="140">
            <template #default="scope">
              {{ scope.row.taskFinishTime || "-" }}
            </template>
          </px-table-column>
          <px-table-column prop="taskHandleTime" label="实际完成时间" min-width="140">
            <template #default="scope">
              {{ scope.row.taskHandleTime || "-" }}
            </template>
          </px-table-column>
          <px-table-column prop="taskStatus" label="任务状态" min-width="100">
            <template #default="scope">
              <TaskStatus :status="scope.row.taskStatus" dark />
            </template>
          </px-table-column>
          <px-table-column prop="taskOwner" label="执行人" min-width="150" />
          <px-table-column prop="taskOwnerPhone" label="联系电话" width="120" />
        </px-table>
      </modelBox>
    </div>
    <div v-if="!isFullscreen" class="full-screen">
      <fullScreen class="icon" @click="toFullScreen" />
    </div>
    <safeDays v-if="isShowSafeDays" v-model="operationDays" v-model:visible="isShowSafeDays" />
  </div>
</template>

<style lang="scss" scoped>
.gas-overview {
  position: relative;
  box-sizing: border-box;
  display: grid;
  grid-template-columns: repeat(24, minmax(16px, 1fr));
  grid-auto-rows: 66px 232px auto;
  grid-auto-flow: column dense;
  grid-gap: 16px;
  width: 100%;
  height: 100%;
  padding: 16px;
  background-color: #001e3bff;

  .full-screen {
    position: absolute;
    top: 6px;
    right: 6px;
    display: flex;
    align-items: center;
    justify-content: center;
    width: 36px;
    height: 36px;
    cursor: pointer;
    background-color: var(--px-color-primary-light-9);
    border-radius: 4px;
    box-shadow: 0 0 4px 0 var(--px-color-primary-light-3);

    .icon {
      width: 70%;
      height: 70%;
      color: var(--px-color-primary);
    }

    &:hover {
      background-color: var(--px-color-primary-light-7);
      box-shadow: none;
    }
  }

  .gas-overview-item {
    display: flex;
    align-items: center;
    justify-content: center;

    .px-button {
      padding-right: 0;
    }
  }

  .one {
    box-sizing: border-box;
    display: flex;
    grid-column: 1 / 25;
    align-items: center;
    justify-content: space-between;
    padding: 0 30px;
    background: url("@/assets/images/overview_header.png") no-repeat;
    background-position: center center;
    background-size: 100% 100%;

    .one-item {
      flex: 1;
      font-size: 18px;
      font-weight: 700;
      line-height: 1;
      color: #fff;
      letter-spacing: 4px;
      background: linear-gradient(to top, #00c2ffff, #fff);
      background-clip: text;
      -webkit-text-fill-color: transparent;
    }

    .one-middle {
      display: flex;
      align-items: center;
      justify-content: center;
      font-size: 28px;
    }

    .one-right {
      display: flex;
      align-items: center;
      justify-content: flex-end;

      .one-days {
        &:hover {
          cursor: pointer;
          background: #fff;
          background-clip: text;
          -webkit-text-fill-color: transparent;
        }
      }
    }
  }

  .two {
    grid-column: 1 / 7;
  }

  .three {
    grid-column: 7 / 21;
  }

  .four {
    grid-column: 21 / 25;
  }

  .five {
    grid-column: 1 / 19;
  }

  .six {
    grid-column: 19 / 25;
  }

  .seven {
    grid-column: 1 / 19;
  }

  .eight {
    grid-column: 19 / 25;
  }

  .all {
    grid-column: 1 / 25;

    &.total {
      height: 232px;
    }
  }

  .dark-table {
    --px-table-border-color: transparent;
    --px-table-border: none;
    --px-table-text-color: #fff;
    --px-table-header-text-color: #fff;
    --px-table-row-hover-bg-color: transparent;
    --px-table-current-row-bg-color: transparent;
    --px-table-header-bg-color: transparent;
    --px-table-bg-color: transparent;
    --px-bg-color: transparent;
    --px-table-tr-bg-color: transparent;
    --px-table-expanded-cell-bg-color: transparent;
  }

  :deep(.px-table--isfixedHeader .px-table__header-wrapper .px-table__cell) {
    color: #fff;
    background-color: transparent !important;
  }

  :deep(.px-table .px-table__header-wrapper th, .px-table .px-table__fixed-header-wrapper th) {
    font-size: 14px !important;
  }

  :deep(.px-table--striped) {
    .px-table__body tr.px-table__row--striped td.px-table__cell {
      background-color: rgb(172 227 255 / 10%);
    }
  }

  :deep(.model-title-com) {
    background-repeat: no-repeat;
    background-size: 276px 32px;
  }

  :deep(.custom-form-ui .px-form-item) {
    margin-bottom: 0 !important;
  }

  :deep(.echarts-chart-dark) {
    border: none;
    box-shadow: none;
  }
}
</style>
